import { Button, Input, NavBar, Toast } from 'antd-mobile'
import { Form } from 'antd-mobile/es/components/form/form'
import React from 'react'
import { useRef } from 'react'
import { API } from '../../utils'

import styles from './index.module.css'

// 用户名验证，长度为5到8，只能出现数字、字母、下划线
const userNameRules = [
  { required: true, message: '用户名不能为空' },
  { pattern: /^\w{5,8}$/, message: '长度为5到8，只能出现数字、字母、下划线' }
]

// 密码验证，长度为5到12，只能出现数字、字母、下划线
const passwordRules = [
  { required: true, message: '用户名不能为空' },
  { pattern: /^\w{5,12}$/, message: '长度为5到12，只能出现数字、字母、下划线' }
]

export default function Registe(props) {
  const form = useRef()

  const handleSubmit = async formInfo => {
    const { username, password } = formInfo
    // 发起网络请求
    const { data: res } = await API.post('/user/registered', { username, password })
    // 注册失败
    if (res.status !== 200) return Toast.show({ icon: 'fail', content: res.description })
    // 注册成功
    Toast.show({
      icon: 'success',
      content: '注册成功！',
      afterClose() {
        props.history.replace('/login')
      }
    })
  }

  const password2Valid = () => {
    const { password, password2 } = form.current.getFieldsValue()
    // 判断前后密码是否一致
    if (password === password2) return Promise.resolve()
    return Promise.reject(new Error('与上面密码不一致!'))
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航 */}
      <NavBar>用户登录</NavBar>

      {/* 登录表单 */}
      <Form
        ref={form}
        className={styles.form}
        onFinish={handleSubmit}
        footer={
          <div className={styles.formSubmit}>
            <Button className={styles.submit} type="submit" size="large" block>
              注 册
            </Button>
          </div>
        }
      >
        <Form.Item name="username" className={styles.formItem} rules={userNameRules}>
          <Input className={styles.input} placeholder="请输入账号" />
        </Form.Item>
        <Form.Item name="password" className={styles.formItem} rules={passwordRules}>
          <Input className={styles.input} type="password" placeholder="请输入密码" />
        </Form.Item>
        <Form.Item
          name="password2"
          className={styles.formItem}
          rules={[...passwordRules, { validator: password2Valid }]}
        >
          <Input className={styles.input} type="password" placeholder="确认密码" />
        </Form.Item>
      </Form>
    </div>
  )
}
